package java2;

import java.awt.*;

/**
 * @Author 不知名网友鑫
 * @Date 2022/5/5
 * Thread方式实现多线程，使用同步代码块方式来解决线程安全问题
 **/
public class ThreadSafeTest1 {
    public static void main(String[] args) {
        Windows1 w1 = new Windows1();
        Windows1 w2 = new Windows1();
        Windows1 w3 = new Windows1();
        w1.start();
        w2.start();
        w3.start();
    }
}
class Windows1 extends Thread{
    private static int ticket  =100;
    @Override
    public void run() {
        while(true) {
            //同步监视器的三种选择：
            //1. Windows1.class/Windows2.class/Windows3.class
            //2. obj：声明为static的obj。
            //3. this：错误的方式
            synchronized (Windows1.class) {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
